package cn.xuewenbao.edu.service.impl;

import cn.xuewenbao.edu.entity.ColumnData;
import cn.xuewenbao.edu.entity.Favorite;
import cn.xuewenbao.edu.entity.vo.MyFavoriteVo;
import cn.xuewenbao.edu.entity.vo.MyLikeOrFavoriteContentVo;
import cn.xuewenbao.edu.mapper.FavoriteMapper;
import cn.xuewenbao.edu.service.*;
import cn.xuewenbao.ucenter.entity.MemberData;
import cn.xuewenbao.ucenter.service.MemberDataService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 收藏表 服务实现类
 * </p>
 *
 * @author mafayu
 * @since 2021-04-21
 */
@Service
public class FavoriteServiceImpl extends ServiceImpl<FavoriteMapper, Favorite> implements FavoriteService {

    @Autowired
    private FavoriteMapper favoriteMapper;
    @Autowired
    private MemberDataService memberDataService;
    @Autowired
    private ColumnDataService columnDataService;
    @Autowired
    private ColumnTypeService columnTypeService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private LikeContentService likeContentService;

    @Override
    public Result<?> hasFavoriteOne(String userId, String contentId, String columnType) {
        Result<Boolean> result = new Result<>();
        QueryWrapper<Favorite> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("content_id", contentId).eq("column_type", columnType);
        Favorite favorite = favoriteMapper.selectOne(wrapper);
        if (favorite == null) {
            result.setSuccess(false);
            result.setMessage("该用户未收藏该目标内容");
            result.setResult(false);
        } else {
            result.setSuccess(true);
            result.setMessage("已收藏");
            result.setResult(true);
        }
        return result;
    }

    @Override
    public Result<?> favoriteContent(String userId, String contentId, String columnType) {
        //检查是否已收藏
        QueryWrapper<Favorite> favoriteQueryWrapper = new QueryWrapper<>();
        favoriteQueryWrapper.eq("user_id", userId).eq("content_id", contentId).eq("column_type", columnType);
        Favorite favorite = baseMapper.selectOne(favoriteQueryWrapper);
        if (favorite != null) {  //已收藏
            return Result.error("重复收藏");
        }
        //添加收藏记录
        favorite = new Favorite();
        favorite.setContentId(contentId);
        favorite.setUserId(userId);
        favorite.setColumnType(columnType);
        baseMapper.insert(favorite);
        //收藏者 favorite_count +1
        QueryWrapper<MemberData> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        MemberData memberData = memberDataService.getOne(wrapper);
        if (memberData == null) {   //用户数据为空, 初始化用户数据
            Boolean addSuccess = memberDataService.addMemberData(userId, 0L, 0L, 1L, 0L, 0L);
            if (!addSuccess) {
                return Result.error("收藏者者用户数据初始化失败");
            }
        } else {
            memberData.setFavoriteCount(memberData.getFavoriteCount() + 1);
            memberDataService.updateById(memberData);
        }

        //内容数据表 favorite_count +1
        QueryWrapper<ColumnData> columnDataQueryWrapper = new QueryWrapper<>();
        columnDataQueryWrapper.eq("content_id", contentId).eq("column_type", columnType);
        ColumnData columnData = columnDataService.getOne(columnDataQueryWrapper);
        if (columnData == null) {
            Boolean addSuccess = columnDataService.addColumnData(contentId, columnType, 0L, 1L, 0L, 0L);
            if (!addSuccess) {
                return Result.error("内容数据初始化失败");
            }
        } else {
            columnData.setFavoriteCount(columnData.getFavoriteCount() + 1);
            columnDataService.updateById(columnData);
        }
        return Result.OK("收藏成功", null);
    }

    @Override
    public Result<?> unfavoriteContent(String contentId, String userId, String columnType) {
        //判断是否已收藏
        QueryWrapper<Favorite> favoriteWrapper = new QueryWrapper<>();
        favoriteWrapper.eq("user_id", userId).eq("content_id", contentId).eq("column_type", columnType);
        int update = baseMapper.delete(favoriteWrapper);
        if (update < 1) {
            return Result.error("收藏表中没有该记录");
        }
        //收藏用户收藏数减一
        QueryWrapper<MemberData> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        MemberData memberData = memberDataService.getOne(wrapper);
        if (memberData == null) {   //未找到user
            return Result.error("用户数据表中未找到该用户");
        }
        if (memberData.getFavoriteCount() < 1) {   //用户收藏数<1, 取消收藏失败
            return Result.error("用户数据表中数据出错");
        }
        memberData.setFavoriteCount(memberData.getFavoriteCount() - 1);
        memberDataService.updateById(memberData);
        //内容数据表收藏数减一
        QueryWrapper<ColumnData> columnDataQueryWrapper = new QueryWrapper<>();
        columnDataQueryWrapper.eq("content_id", contentId).eq("column_type", columnType);
        ColumnData columnData = columnDataService.getOne(columnDataQueryWrapper);
        if (columnData == null) {
            return Result.error("内容数据表中未找到信息");
        }
        if (columnData.getFavoriteCount() < 1) {
            return Result.error("内容数据表中的数据出错");
        }
        columnData.setFavoriteCount(columnData.getFavoriteCount() - 1);
        columnDataService.updateById(columnData);
        return Result.OK("取消收藏成功", null);
    }

    @Override
    public Result<?> favoriteList(String userId, String columnType) {
        //最终要返回的 myFavoriteVo列表
        List<MyFavoriteVo> voList = new ArrayList<>();
        //获取原始的 favorite列表
        QueryWrapper<Favorite> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("column_type", columnType);
        List<Favorite> favoriteList = baseMapper.selectList(wrapper);
        for (Favorite favorite : favoriteList) {   //对每个原始 favorite获取完整的 myFavoriteVo
            //获取 MyFavoriteVo的 contentId userId columnType
            MyFavoriteVo vo = new MyFavoriteVo();
            BeanUtils.copyProperties(favorite, vo);
            vo.setColumnType(columnType);
            //获取 MyFavoriteVo的 title cover viewCount
            String tableName = columnTypeService.getColumnTypeById(columnType);
            if (tableName == null) {
                return Result.error("收藏内容的类型columnType不正确");
            }
            MyLikeOrFavoriteContentVo contentVo = columnTypeService.selectMyLikeOrFavoriteContent(favorite.getContentId(), tableName);
            if (contentVo == null) {
                continue;
            }
            BeanUtils.copyProperties(contentVo, vo);
            //获取 MyFavoriteVo的 likeCount favoriteCount commentCount;
            QueryWrapper<ColumnData> columnDataWrapper = new QueryWrapper<>();
            columnDataWrapper.eq("content_id", favorite.getContentId()).eq("column_type", columnType);
            ColumnData data = columnDataService.getOne(columnDataWrapper);
            if (data == null) {
                continue;
            }
            BeanUtils.copyProperties(data, vo);
            //获取 MyFavoriteVo的 commentCount isLike isFavorite;
            Long count = commentService.getCommentCount(favorite.getContentId(), columnType);
            vo.setCommentCount(count);
            boolean isFavorite = hasFavoriteOne(userId, favorite.getContentId(), columnType).isSuccess();
            vo.setIsFavorite(isFavorite);
            boolean isLike = likeContentService.hasLikeOne(userId, favorite.getContentId(), columnType).isSuccess();
            vo.setIsLike(isLike);
            voList.add(vo);
        }
        return Result.OK("获取收藏列表成功！", voList);
    }

    @Override
    public Result<?> hasFavoriteOne(String userId, String courseId) {
        Result<Boolean> result = new Result<>();
        QueryWrapper<Favorite> favoriteQueryWrapper = new QueryWrapper<>();
        favoriteQueryWrapper.eq("content_id",courseId).eq("user_id",userId);
        Favorite favorite = baseMapper.selectOne(favoriteQueryWrapper);
        if (favorite==null){
            result.setSuccess(false);
            result.setMessage("该用户未收藏");
            result.setResult(false);
        } else {
            result.setSuccess(true);
            result.setMessage("已收藏");
            result.setResult(true);
        }
        return result;
    }

    @Override
    public Long totalNum(String courseId) {
        QueryWrapper<Favorite> favoriteQueryWrapper = new QueryWrapper<>();
        favoriteQueryWrapper.eq("content_id",courseId);
        Integer selectCount = baseMapper.selectCount(favoriteQueryWrapper);
        return Long.valueOf(selectCount);
    }
}
